<?php
namespace app\index\service;


use app\common\JwtToken;
use app\common\model\UserModel;
use app\common\model\SmsCodeModel;

class UserService
{
    private static $model;

    public function __construct(UserModel $model)
    {
        self::$model = $model;
    }

    /**
     *
     * User: zhouyao
     * Date: 2018/11/27
     * Time: 5:39 PM
     * @param $params
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @return mixed
     */
    public function create($params)
    {
        if (empty($params) || !isset($params['account_name']) || !isset($params['password']) || !isset($params['type'])) {
            return app_fail(9983);
        }
        // 查看用户是否存在
        $ext = self::$model->where(['account_name' => $params['account_name'], 'phone' => $params['phone']])->find();
        if (!empty($ext)) {
            return app_fail(9995);
        }
        $params['password'] = md5($params['password']);
        $params['create_time'] = $params['update_time'] = time();
        try {
            $row = self::$model->allowField(true)->save($params);
            return $row;
        } catch (\Exception $e) {
            return app_fail(9998);
        }
    }

    /**
     * 管理员登录
     * User: zhouyao
     * Date: 2018/11/27
     * Time: 5:57 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function login($params)
    {
        if (empty($params) || !isset($params['groupname']) || !isset($params['password'])) {
            return app_fail(9997);
        }

        $user = self::$model->where(['account_name' => $params['groupname']])
            ->where('type', '<', 3)
            ->find();

        if (empty($user)) {
            return app_fail(7999);
        }

        if ($user['password'] != md5($params['password'])) {
            return app_fail(7997);
        }
        $path = config('param_config.imagePath');
        $filePath = config('app.app_host').substr($path, 1);
        // 生成 token
        $token = JwtToken::createToken($user['id']);

        return [
            'tokenId' => $token,
            'imgurl' => $user['imgurl'] ? $filePath.$user['imgurl'] : '',
            'nickname' => $user['nickname'],
            'remark' => $user['remark']
        ];
    }

    /**
     * 发送验证码
     * User: zhouyao
     * Date: 2018/11/27
     * Time: 8:35 PM
     * @param $params
     * @throws \app\common\exception\AppException
     * @return mixed
     */
    public function sendCode($params)
    {
        if (empty($params) || !isset($params['phone'])) {
            return app_fail(9997);
        }

        if (mb_strlen($params['phone']) != 11) {
            return app_fail(9987);
        }

        $smsCode = mt_rand(100000, 999999);
        try{
            app_sms($params['phone'], (String) $smsCode);
            $smsCodeModel = new SmsCodeModel();
            $data['phone'] = $params['phone'];
            $data['code'] = $smsCode;
            $data['create_time'] = $data['update_time'] = time();
            return $smsCodeModel->save($data) ? true : false;
        }catch (\Exception $e){
            return app_fail(9991);//验证码发送失败
        }
    }

    /**
     * 更改用户密码
     * User: zhouyao
     * Date: 2018/11/27
     * Time: 8:43 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @return
     */
    public function updatePwd($params)
    {
        if (empty($params) || !isset($params['tokenId']) || !isset($params['oldpwd']) || !isset($params['newpwd'])) {
            return app_fail(9997);
        }

        $user = self::$model->where(['id' => $params['tokenId']])->find();
        if (empty($user)) {
            return app_fail(9998);
        }

        if ($user['password'] != md5($params['oldpwd'])) {
            return app_fail(9982);
        }

        try {
            self::$model->save(['password' => md5($params['newpwd'])], ['id' => $params['tokenId']]);
            return true;
        } catch (\Exception $e) {
            return app_fail(9899);
        }
    }

    /**
     * 修改头像信息
     * User: zhouyao
     * Date: 2018/11/27
     * Time: 9:00 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     */
    public function  updateImg($params)
    {
        if (empty($params) || !isset($params['tokenId']) || !isset($params['image'])) {
            return app_fail(9997);
        }

        $path = config('param_config.imagePath');
        $info = $params['image']->move($path);
        $data = ['imgurl' => ''];
        if($info){
            $data['imgurl'] = $info->getSaveName();
        }else{
            // 上传失败获取错误信息
            app_fail(9981);
        }

       
        try {
            self::$model->save($data, ['id' => $params['tokenId']]);
            $filePath = config('app.app_host').substr($path, 1);
            return ['url' => $filePath . $data['imgurl']];
        } catch (\Exception $e) {
            return app_fail(9899);
        }
    }

    /**
     * 获取用户信息
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function userInfo($params)
    {
        if (empty($params) || !isset($params['tokenId'])) {
            return app_fail(9997);
        }

        // 查询指定用户信息
        $user = self::$model->where(['id' => $params['tokenId']])->find();
        if (empty($user)) {
            return app_fail(9977);
        }
        $user['imgurl'] = 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/image/' . $user['imgurl'];
        return $user;
    }
}